// 交错字符串

package Leetcode;

class solution_097 {
    public boolean isInterleave(String s1, String s2, String s3) {
        int pointer1 = 0, pointer2 = 0, pointer3 = 0;
        if (s3.length() != s1.length() + s2.length())
            return false;
        return recursion(s1, s2, s3, pointer1, pointer2, pointer3);

    }

    public boolean recursion(String s1, String s2, String s3, int pointer1, int pointer2, int pointer3) {
        for (int i = pointer3; i < s3.length(); i++) {
            char c = s3.charAt(i);
            boolean sign1 = false;
            boolean sign2 = false;
            if (pointer1 < s1.length() && c == s1.charAt(pointer1)) {
                sign1 = true;
            }
            if (pointer2 < s2.length() && c == s2.charAt(pointer2)) {
                sign2 = true;
            }
            if (sign1 == false && sign2 == false)
                return false;
            else if (sign1 == false && sign2 == true)
                pointer2++;
            else if (sign1 == true && sign2 == false)
                pointer1++;
            else {
                return recursion(s1, s2, s3, pointer1 + 1, pointer2, i + 1)
                        | recursion(s1, s2, s3, pointer1, pointer2 + 1, i + 1);
            }
        }
        return true;
    }
}

public class Solution097 {
    public boolean isInterleave(String s1, String s2, String s3) {
        int m = s1.length();
        int n = s2.length();
        int t = s3.length();
        // 长度不相等直接剪枝
        if (m + n != t)
            return false;
        boolean[][] dp = new boolean[m + 1][n + 1];
        dp[0][0] = true;
        for (int i = 0; i <= m; i++)
            for (int j = 0; j <= n; j++) {

                if (i > 0 && s1.charAt(i - 1) == s3.charAt(i + j - 1))
                    dp[i][j] |= dp[i - 1][j];

                if (j > 0 && s2.charAt(j - 1) == s3.charAt(i + j - 1))
                    dp[i][j] |= dp[i][j - 1];
            }
        return dp[m][n];
    }
}
